package cn.jstars.datatocloud.common.conf.datasource;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import com.alibaba.druid.pool.DruidDataSource;

/**
 * DataSource Config Class
 * 
 * @version 2018/05/28 16:32:49
 * @author zhu_longxiang
 *
 */
@Configuration
@MapperScan(basePackages = "cn.jstars.datatocloud.modules.*.dao", sqlSessionTemplateRef = "counton2SqlSessionTemplate")
public class ConfigDataSource {

	/**
	 * set DataSource
	 * 
	 * @return DataSource
	 */
	@Bean(name = "counton2Ds")
	@ConfigurationProperties(prefix = "spring.datasource.counton2")
	@Primary
	public DataSource setDataSource() {
		return DataSourceBuilder.create().build();
	}

	/**
	 * set Transaction Manager
	 * 
	 * @param dataSource
	 *            DataSource
	 * @return DataSource Transaction Manager
	 */
	@Bean(name = "counton2TransactionManager")
	@Primary
	public DataSourceTransactionManager setTransactionManager(@Qualifier("counton2Ds") DataSource dataSource) {
		return new DataSourceTransactionManager(new DruidDataSource());
	}

	/**
	 * set SqlSession Factory
	 * 
	 * @param dataSource
	 *            dataSource
	 * @return SqlSessionFactory
	 * @throws Exception
	 *             Exception
	 */
	@Bean(name = "counton2SqlSessionFactory")
	@Primary
	public SqlSessionFactory setSqlSessionFactory(@Qualifier("counton2Ds") DataSource dataSource) throws Exception {
		SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
		bean.setDataSource(dataSource);
		bean.setMapperLocations(
				new PathMatchingResourcePatternResolver().getResources("classpath:mappers/counton2/*.xml"));

		return bean.getObject();
	}

	/**
	 * set SqlSession Template
	 * 
	 * @param sqlSessionFactory
	 *            sqlSessionFactory
	 * @return SqlSessionTemplate
	 * @throws Exception
	 *             Exception
	 */
	@Bean(name = "counton2SqlSessionTemplate")
	@Primary
	public SqlSessionTemplate setSqlSessionTemplate(
			@Qualifier("counton2SqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
		return new SqlSessionTemplate(sqlSessionFactory);
	}

}
